package psn.zjk.common.serialize;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;

/**
 * @USER white
 * @DATETIME 2021/1/7 22:23
 */
public class HessianDemo {

    public static <T> byte[] pack(T t) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        Hessian2Output hessian2Output = new Hessian2Output(byteArrayOutputStream);
        hessian2Output.writeObject(t);
        //注意关闭流
        hessian2Output.close();
        return byteArrayOutputStream.toByteArray();
    }

    public static <T> T unpack(byte[] bytes) throws IOException {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        Hessian2Input hessian2Input = new Hessian2Input(byteArrayInputStream);
        Object o = hessian2Input.readObject();
        return (T) o;
    }


    public static void main(String[] args) throws IOException {
        User user = new User();
        user.name = "name";
        user.sex = "sex";
        long l = System.currentTimeMillis();
        for (int i = 0; i < 10000000; i++) {
            byte[] pack = HessianDemo.pack(user);
//            User unpack = HessianDemo.unpack(pack);
//            System.out.println(unpack.sex);
//            System.out.println(unpack.name);
        }
        System.out.println(System.currentTimeMillis()-l);
    }


    static class User implements Serializable {

        private String name;
        private String sex;


        public String getSex() {
            return sex;
        }
    }

}
